package cn.lds.springbootmybatisplusexamplej380.controller;

import cn.lds.springbootmybatisplusexamplej380.dto.ResponseDTO;
import cn.lds.springbootmybatisplusexamplej380.entity.Dept;
import cn.lds.springbootmybatisplusexamplej380.entity.Emp;
import cn.lds.springbootmybatisplusexamplej380.service.DeptService;
import cn.lds.springbootmybatisplusexamplej380.service.EmpService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/emp/")
public class EmpController {

    @Resource
    private EmpService empService;
    @Resource
    private DeptService deptService;

    private final Logger log = LoggerFactory.getLogger(EmpController.class);

    @GetMapping("query_emps")
    public String queryEmp(Model model){

        ResponseDTO<List<Emp>> listResponseDTO = empService.selectEmpAll();

        log.info("info:{}",listResponseDTO.getData());

        model.addAttribute("result",listResponseDTO);

        return "show_emps";

    }
    @GetMapping("/{id}")
    public String query_emp_id(@PathVariable Integer id,Model model){
        ResponseDTO<Emp> empResponseDTO = empService.selectEmpById(id);
        model.addAttribute("result",empResponseDTO);
        return "show_emp_id";
    }

    @GetMapping("/remove/{id}")
    public String remove_emp(@PathVariable Integer id){
        empService.removeEmpById(id);

        return "redirect:/emp/query_emps";
    }

    @GetMapping("/add_emp")
    public String addEmp(Model model){

        ResponseDTO<List<Dept>> listResponseDTO = deptService.selectDeptAll();
        model.addAttribute("depts",listResponseDTO.getData());

        return "add_emp";
    }

    @PostMapping("/do_add_emp")
    public String doAddEmp(Emp emp){

        log.info("info:{}",emp);

        empService.insertEmp(emp);

        return "redirect:/emp/query_emps";
    }

    @GetMapping("modify_emp/{id}")
    public String modiyEmp(@PathVariable Integer id,Model model){

        ResponseDTO<Emp> empResponseDTO = empService.selectEmpById(id);

        model.addAttribute("emp",empResponseDTO.getData());

        ResponseDTO<List<Dept>> listResponseDTO = deptService.selectDeptAll();

        model.addAttribute("depts",listResponseDTO.getData());

        return "modify_emp";

    }

    @PostMapping("/do_modify_emp")
    public String doModifyEmp(Emp emp){
        empService.modifyEmp(emp);

        return "redirect:/emp/query_emps";
    }


}
